﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Catan
{
    class RoadMap
    {
        private readonly byte[][] _Roads;

        private const byte Unusable = 0;
        private const byte Unused = 1;


        public RoadMap()
        {
            const int height = 11;
            const int width = 10;

            _Roads = new byte[height][];
            for (int y = 0; y < height; y += 1)
            {
                byte[] roadSegment = new byte[width];

                for (int x = 0; x < width; x += 1)
                {
                    roadSegment[x] = Unusable;
                    if ((y == 0 || y == 10) && (x > 1 && x < 8))
                    {
                        roadSegment[x] = Unused;
                    }
                    else if ((y == 1 || y == 9) && (x > 2 && x < 7))
                    {
                        roadSegment[x] = Unused;
                    }
                    else if ((y == 2 || y == 8) && (x > 0 && x < 9))
                    {
                        roadSegment[x] = Unused;
                    }
                    else if ((y == 3 || y == 7) && (x % 2 == 1))
                    {
                        roadSegment[x] = Unused;
                    }
                    else if (y == 4 || y == 6)
                    {
                        roadSegment[x] = Unused;
                    }
                    else if ((y == 5) && (x > 1 && x < 8))
                    {
                        roadSegment[x] = Unused;
                    }
                }

                _Roads[y] = roadSegment;
            }
        }


        public bool LayRoad(Player owner, byte x, byte y)
        {
            if (y < 0 || y >= _Roads.Length)
            {
                throw new ArgumentOutOfRangeException("y");
            }

            byte[] roadSection = _Roads[y];
            if (x < 0 || x >= roadSection.Length)
            {
                throw new ArgumentOutOfRangeException("x");
            }

            byte currentValue = roadSection[x];
            if (currentValue == Unusable)
            {
                throw new InvalidOperationException("The road location is used internally and cannot be set.");
            }

            if (roadSection[x] != Unused)
            {
                return false;
            }

            roadSection[x] = owner.Id;
            return true;
        }
    }
}
